package schedule

import "time"

// ScheduleHandler 定时处理接口
type ScheduleHandler interface {
	Handle(int64)
}

// Schedule 定时处理
type Schedule struct {
	ticker  *time.Ticker
	queue   chan int64
	handler ScheduleHandler
}

// NewSchedule 创建Schedule
func NewSchedule(handler ScheduleHandler) *Schedule {
	return &Schedule{
		ticker:  time.NewTicker(time.Second),
		queue:   make(chan int64, 3600),
		handler: handler,
	}
}

// Start 开始
func (s *Schedule) Start() {
	go func() {
		for t := range s.ticker.C {
			s.push(t.Unix())
		}
	}()
	go func() {
		for ts := range s.queue {
			s.pop(ts)
		}
	}()
}

func (s *Schedule) push(ts int64) {
	go func() { s.queue <- ts }()
}

func (s *Schedule) pop(ts int64) {
	go func() { s.handler.Handle(ts) }()
}
